<template>
  <a-card class="general-card" title="站内信" :bordered="false">
    <a-tabs>
      <a-tab-pane key="MESSAGE" title="站内信列表">
        <PickSearchColumn :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
        </PickSearchColumn>
        <a-button style="margin-bottom: 10px" type="primary"  @click="sendMessageClick">发送消息</a-button>
        <PickTablePage ref="messageTablePageRef" :columns="messageColumns" :methods="messagSortMethods" :api="getMessagePage" @delete="handleMassageDelete"
                   :api-params="apiParams" :bordered="true">
            <template #details="{ data }" >
              <a-button @click="handleMassageDetails(data)" type="text" status="success">详细</a-button>
            </template>
          </PickTablePage>
      </a-tab-pane>
      <a-tab-pane key="SETTING" title="通知类站内信">
        <PickTablePage ref="settingTablePageRef" :columns="noticeColumns" :methods="noticeSortMethods" :api="getNoticeMessageData" :bordered="true">
          <template #noticeStatus="{ data }">
            <p v-if="data.noticeStatus == 'OPEN'"><a-badge status="success" /> 开启</p>
            <p v-if="data.noticeStatus == 'CLOSE'"><a-badge status="danger" /> 关闭</p>
          </template>
          <template #update="{ data }">
            <a-button v-if="data.noticeStatus == 'CLOSE'" @click="updateClick(data)" type="text" status="success">开启</a-button>
            <a-button v-if="data.noticeStatus == 'OPEN'" @click="updateClick(data)"  type="text" status="danger" >关闭</a-button>
          </template>
          <template #edit="{ data }"><a-button @click="editClick(data)" type='text' status="warning">编辑</a-button></template>
        </PickTablePage>
      </a-tab-pane>
    </a-tabs>
    <!--发送站内信-->
    <a-modal v-model:visible="messageFormData.messageSendModal" :align-center="false" :footer="false" :width="800">
        <template #title>{{messageFormData.isAdd?'发送站内信':'消息详情'}}</template>
        <a-form ref="formRef" :model="messageFormData.messageSendForm" :disabled="!messageFormData.isAdd">
            <a-form-item field="title" label="消息标题" :rules="[REQUIRED]">
                <a-input v-model="messageFormData.messageSendForm.title" :style="{ width: '400px' }" />
            </a-form-item>
            <a-form-item field="content" label="消息内容" :rules="[REQUIRED]">
                <a-textarea v-model="messageFormData.messageSendForm.content" allow-clear :style="{ width: '400px' }" />
            </a-form-item>
            <a-form-item field="messageClient" label="发送对象">
                <a-radio-group type="button" v-model="messageFormData.messageSendForm.messageClient" @change="messageFormData.messageSendForm.messageRange = 'ALL'">
                    <a-radio value="member">会员</a-radio>
                    <a-radio value="store">商家</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item field="messageRange" label="发送范围">
                <a-radio-group type="button" v-model="messageFormData.messageSendForm.messageRange">
                    <a-radio value="ALL">全站</a-radio>
                    <a-radio value="MEMBER" v-if="messageFormData.messageSendForm.messageClient == 'member'">指定会员</a-radio>
                    <a-radio value="APPOINT" v-if="messageFormData.messageSendForm.messageClient == 'store'">指定商家</a-radio>
                </a-radio-group>
            </a-form-item>
            <template v-if="messageFormData.isAdd">
              <a-form-item label="指定会员" v-if="messageFormData.messageSendForm.messageClient == 'member' && messageFormData.messageSendForm.messageRange == 'MEMBER'">
                <div>
                  <a-button type="outline" :style="{marginBottom: '10px'}" @click="addVip"><template #default>选择会员</template></a-button>
                  <PickTablePage ref="memberTablePageRef" :columns="memberColumns" :methods="memberSortMethods" :dataList="selectedMember" :enablePagination="false">
                    <template #delete="{ rowIndex }"><a-button @click="deleteMember(rowIndex)" type='text' status="danger">删除</a-button></template>
                  </PickTablePage>
                </div>
              </a-form-item>
              <a-form-item label="指定商家" v-if="messageFormData.messageSendForm.messageClient == 'store' && messageFormData.messageSendForm.messageRange == 'APPOINT'">
                <a-select v-model="messageFormData.messageSendForm.store" :default-value="messageFormData.messageSendForm.store"
                          :style="{width:'500px'}" placeholder="请选择" multiple @change="appointChange">
                  <a-option v-for="(item, index) in messageFormData.shopList" :key="index" :value="item.id+'--'+item.storeName">{{item.storeName}}</a-option>
                </a-select>
              </a-form-item>
            </template>
            <template v-else>
              <a-form-item label="指定会员" v-if="messageFormData.messageSendForm.messageClient == 'member'" :disabled="false">
                <PickTablePage ref="memberMessageRef" :columns="memberMessageColumns" :api="getMemberMessage" :api-params="messageFormData.searchMessageParams">
                  <template #status="{ data }">
                    <p v-if="data.status == 'ALREADY_READY'"><a-badge status="success" /> 已读</p>
                    <p v-else-if="data.status == 'UN_READY'"><a-badge status="warning" /> 未读</p>
                    <p v-else><a-badge status="danger" /> 回收站</p>
                  </template>
                </PickTablePage>
              </a-form-item>
              <a-form-item label="指定商家" v-if="messageFormData.messageSendForm.messageClient == 'store'">
                <PickTablePage ref="shopMessageRef" :columns="shopMessageColumns" :api="getShopMessage" :api-params="messageFormData.searchMessageParams">
                  <template #status="{ data }">
                    <p v-if="data.status == 'ALREADY_READY'"><a-badge status="success" /> 已读</p>
                    <p v-else-if="data.status == 'UN_READY'"><a-badge status="warning" /> 未读</p>
                    <p v-else><a-badge status="danger" /> 回收站</p>
                  </template>
                </PickTablePage>
              </a-form-item>
            </template>
            <a-form-item label="操作">
                <a-button type="primary"  @click="handleSubmit">提交</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
    <!--会员选择器-->
    <a-modal v-model:visible="checkUserList" width="1200px">
        <template #title>会员选择器</template>
        <userList ref="memberLayout" @callback="callbackSelectUser" :selectedList="selectedMember"></userList>
    </a-modal>
    <!--站内信模板编辑-->
    <a-modal v-model:visible="messageFormData.templateEditModal" :align-center="false" :footer="false" :width="800">
      <template #title>编辑通知类推送</template>
      <div class="message-title">
        <p>1、左侧#{xxx}为消息变量</p>
        <p>2、如果要发送的消息包含消息变量则将消息变量复制到消息内容中即可，注意格式</p>
        <p>3、例：比如消息变量为#{订单号}，发送的内容为：订单号为xxx的订单已经发货注意查收，完整的消息内容应该为订单号为#{订单号}的订单已经发货注意查收</p>
      </div>
      <div class="send-setting">
        <div class="left-show">
          <div v-for="(item, index) in messageFormData.templateEditForm.variables" :key="index">#{<span>{{item}}</span>}</div>
        </div>
        <div class="send-form">
          <a-form ref="templateEditFormRef" :model="messageFormData.templateEditForm">
            <a-form-item field="noticeNode" label="通知节点" :rules="[REQUIRED]" disabled>
              <a-input v-model="messageFormData.templateEditForm.noticeNode" />
            </a-form-item>
            <a-form-item field="noticeTitle" label="消息标题" :rules="[REQUIRED]">
              <a-input v-model="messageFormData.templateEditForm.noticeTitle" />
            </a-form-item>
            <a-form-item field="noticeContent" label="消息内容" :rules="[REQUIRED]">
              <a-textarea  v-model="messageFormData.templateEditForm.noticeContent" allow-clear max-length="50" :auto-size="{maxRows:3,minRows: 3}" show-word-limit />
            </a-form-item>
            <a-form-item label="操作">
              <a-button type="primary" @click="templateEditFormSubmit">保存</a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>
<script lang="ts" setup>

import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';
import {ColumnsDataRule, SearchRule,MethodsRule} from '@/types/global';
import{ getNoticeMessageData, updateMessageStatus, editNoticeMessage ,getMessagePage, sendMessage, getShopMessage, getMemberMessage, deleteMessage, getNoticeMessageDetail } from '@/api/operation';
import { ref, watch, reactive, onMounted } from 'vue';
import { VARCHAR255, REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
import { getShopList } from '@/api/shops';
import { saveActivityCoupon } from '@/api/promotion';
import userList from '@/views/member/member-list/list.vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { Message } from '@arco-design/web-vue';
import { messageClientStatus, messageRangeStatus } from '@/utils/tools';
import useCurrentInstance from '@/hooks/useCurrentInstance';

const modal = useCurrentInstance().globalProperties?.$modal; // 获取modal
const messageTablePageRef = ref<any>();
const apiParams = ref({});
const settingTablePageRef = ref<any>();
const shopMessageRef = ref<any>();
const memberMessageRef = ref<any>();
const templateEditFormRef = ref<any>();
const memberTablePageRef = ref<any>();
const columnsSearch :Array<SearchRule> = [
    {label:"消息标题", model:"title", disabled:false, input:true},
    {label:"消息内容", model:"content", disabled:false, input:true}
];
const messageColumns :ColumnsDataRule[] = [
    {title:"消息标题", dataIndex:'title'},
    {title:"消息内容", dataIndex:'content',width:500},
    {title:"发送对象", dataIndex:'messageClient',slot: true,slotData: {badge: messageClientStatus}},
    {title:"发送类型", dataIndex:'messageRange',slot: true,slotData: {badge: messageRangeStatus}},
    {title:"发送时间", dataIndex:'createTime'},
];
const memberColumns :ColumnsDataRule[] = [
  {title: '用户名称', dataIndex: 'nickName'},
  {title: '手机号', dataIndex: 'mobile'},
];
const noticeColumns :ColumnsDataRule[] = [
    {title:"通知节点", dataIndex:'noticeNode'},
    {title:"通知标题", dataIndex:'noticeTitle'},
    {title:"通知内容", dataIndex:'noticeContent'},
    {title:"状态", dataIndex:'noticeStatus', width: 150, slot: true, slotTemplate: 'noticeStatus'},
];
const shopMessageColumns :ColumnsDataRule[] = [
  {title: '店铺ID', dataIndex: 'memberId'},
  {title: '店铺名称', dataIndex: 'memberName'},
  {title: '是否已读', dataIndex: 'status',slot: true, slotTemplate: 'status'}
];
const memberMessageColumns :ColumnsDataRule[] = [
  {title: '会员ID', dataIndex: 'memberId'},
  {title: '会员名称', dataIndex: 'memberName'},
  {title: '是否已读', dataIndex: 'status',slot: true, slotTemplate: 'status'}
];
const messagSortMethods :MethodsRule = {
    title:'操作',
    methods:[
      {title:'详细', callback:'details', slot: true, slotTemplate: 'details'},
      {title:'删除', callback:'delete', type:'text', status:"danger"}
    ]
};
const noticeSortMethods :MethodsRule = {
    title:'操作',
    width: 250,
    methods:[
      {title:'更新', callback:'update', slot: true, slotTemplate: 'update'},
      {title:'编辑', callback:'edit', slot: true, slotTemplate: 'edit'}
    ]
};
const memberSortMethods :MethodsRule = {
  title: '操作',
  methods: [
    {title: '删除', callback: 'delete', slot: true, slotTemplate: 'delete'}
  ]
};
const formRef = ref<any>();
const checkUserList = ref<boolean>(false); // 选择会员弹框是否显示
const memberLayout = ref(null) as any; // 选择会员
const selectedMember = ref<Array<any>>([]); // 已选会员列表数据
interface formInterface {
  messageSendForm: any,
  messageSendModal: boolean,
  shopList: Array<any>,
  isAdd: boolean,
  searchMessageParams: any,
  shopMessageData: Array<any>,
  memberMessageData: Array<any>,
  templateEditModal: boolean,
  templateEditForm: any,
}
const messageFormData :formInterface = reactive({
  messageSendForm: {
    title: '', // 消息标题
    content: '', // 消息内容
    messageClient: 'member', // 发送对象
    messageRange: 'ALL', // 发送范围
    userIds: [], // 指定商家
    memberDTOS: [],
    store: [],
  },
  messageSendModal: false,
  shopList: [],// 店铺列表
  isAdd: false, // 是否为添加（添加true,详细false）
  searchMessageParams: {},  // 发送消息详情入参
  shopMessageData: [],  // 发送给店铺的消息数据
  memberMessageData: [],  // 发送给会员的消息数据
  templateEditModal: false, // 站内信模板编辑
  templateEditForm: {}, // 站内信模板编辑表单
});
// 获取全部商家
const getShopListAll = async () => {
  const res = await getShopList();
  if (res.data.success) {
    messageFormData.shopList = res.data.result;
  }
};
// 发送消息
const sendMessageClick = () => {
  messageFormData.isAdd = true;
  messageFormData.messageSendModal = true;
  formRef.value.resetFields();
  selectedMember.value = [];
  messageFormData.messageSendForm.store = [];
};
// 更新选择的会员
const reSelectMember = () => {
  messageFormData.messageSendForm.memberDTOS = selectedMember.value.map((item: any) => {
    return { nickName: item.nickName, id: item.id };
  })
};
// 选择会员
const addVip = () => {
  memberLayout.value.selectedMember = false;
  checkUserList.value = true;
};
// 子组件传过来的值
const callbackSelectUser = (val: any): void => {
  // 每次将返回的数据回调判断
  const findUser = selectedMember.value.find((item: any) => item.id === val.id) as any;
  // 如果没有则添加
  if (findUser && findUser.id) {
    // 有重复数据就删除
    selectedMember.value.forEach((item: any, index: any) => {
      if (item.id === findUser.id) {
        selectedMember.value.splice(index, 1)
      }
    })
  } else {
    selectedMember.value.push({ ...val })
  }
  reSelectMember()
};
// 选择商家
const appointChange = (value: any) => {
  messageFormData.messageSendForm.userIds = value.map((item: any) => item.split('--')[0]);
  messageFormData.messageSendForm.userNames = value.map((item: any) => item.split('--')[1]);
};
// 提交
const handleSubmit = async () => {
  const params = JSON.parse(JSON.stringify(messageFormData.messageSendForm));
  const auth = await formRef.value?.validate();
  const userIds = [] as Array<any>;
  const userNames = [] as Array<any>;
  // 会员--指定会员
  if (messageFormData.messageSendForm.messageClient == 'member' && messageFormData.messageSendForm.messageRange == 'MEMBER') {
    messageFormData.messageSendForm.memberDTOS.forEach((item: any) => {
      userIds.push(item.id);
      userNames.push(item.nickName);
    });
    params.userIds = userIds;
    params.userNames = userNames;
  }
  // 商家--指定商家
  if (messageFormData.messageSendForm.messageClient == 'store' && messageFormData.messageSendForm.messageRange == 'APPOINT') {
    if (messageFormData.messageSendForm.userIds.length <= 0 ) {
      Message.error('请选择发送范围！');
      return;
    }
  }
  delete params.store;
  if (!auth) {
    sendMessage(params).then((res: any) => {
      Message.success("发送成功");
      messageFormData.messageSendModal = false;
      messageTablePageRef.value.init();
    })
  }
}
// 删除站内信
const handleMassageDelete = async (val: any) => {
  modal.confirm({
    title: '确认删除',
    content: `您确认删除此站内信?`,
    alignCenter: false,
    onOk: async () => {
      const res = await deleteMessage(val.record.id);
      if (res.data.success) {
        Message.success('删除成功');
        messageTablePageRef.value.init();
      }
    },
  });
}
const messageDetail = async () => {
  if (messageFormData.messageSendForm.messageClient == 'member') {
    // 会员
    memberMessageRef.value.init();
  } else {
    // 商家
    shopMessageRef.value.init();
  }
};
// 管理员获取发送详情列表
const handleMassageDetails = (val: any) => {
  messageFormData.isAdd = false;
  messageFormData.messageSendModal = true;
  messageFormData.searchMessageParams.messageId = val.id;
  messageFormData.messageSendForm = val;
  messageDetail();
}
// 更新通知类站内信状态
const updateClick = async (data: any) => {
  if (data.noticeStatus == 'CLOSE') {
    // 开启
    const res = await updateMessageStatus(data.id, "OPEN");
    if (res.data.success) {
      Message.success('启用成功');
      settingTablePageRef.value.init();
    }
  } else if (data.noticeStatus == 'OPEN') {
    // 关闭
    const res = await updateMessageStatus(data.id, "CLOSE");
    if (res.data.success) {
      Message.success('禁用成功');
      settingTablePageRef.value.init();
    }
  }
}
// 通知站内信编辑
const editClick = async (data: any) => {
  messageFormData.templateEditModal = true;
  const res = await getNoticeMessageDetail(data.id);
  if (res.data.success) {
    messageFormData.templateEditForm = res.data.result;
  }
}
// 通知站内信编辑提交
const templateEditFormSubmit = async () => {
  const auth = await templateEditFormRef.value?.validate();
  if (!auth) {
    const params = {
      noticeContent: messageFormData.templateEditForm.noticeContent,
      noticeTitle: messageFormData.templateEditForm.noticeTitle
    }
    editNoticeMessage(messageFormData.templateEditForm.id, params).then(res => {
      if (res.data.success) {
        messageFormData.templateEditModal = false;
        Message.success('保存成功！');
        settingTablePageRef.value.init();
      }
    })
  }
}
// 删除商品
const  deleteMember = (index :any) => {
  selectedMember.value.splice(index, 1);
  reSelectMember();
}
onMounted(() => {
  getShopListAll();
})
</script>

<style scoped lang="less">
.message-title{
  background-color: #fff5eb;
  border: 1px solid #ffc999;
  box-sizing: border-box;
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  padding: 8px 15px;
  border-radius: 2px;
  p {
    margin: 4px 0;
  }
}
.send-setting {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  .left-show {
    width: 230px;
    padding: 20px 30px 20px 10px;
    border: 1px solid #eee;
    background-color: #fafafa;
  }
  .send-form {
    flex: 1;
    padding: 10px;
    border: 1px solid #eee;
    margin-left: 24px;
    background-color: #fafafa;
  }
}
</style>
